import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/model/websocket_model.dart';
import 'package:labcloud_app/page/user/login.dart';

class Message extends StatefulWidget {
  const Message({super.key});

  @override
  State<Message> createState() => _MessageState();
}

class _MessageState extends State<Message> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final userModel = Provider.of<UserModel>(context);
    final websocketModel = Provider.of<WebSocketModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('消息页'),

        actions: [
          IconButton(
            icon: Icon(
              websocketModel.connected ? Icons.cloud_done : Icons.cloud_off,
              color: websocketModel.connected ? Colors.green : Colors.red,
            ),
            onPressed: () {
              // 切换连接状态
              if (websocketModel.connected) {
                websocketModel.disconnect();
              } else {
                // 这里使用一个示例WebSocket URL，实际项目中应替换为你的服务器地址
                websocketModel.connect('ws://192.168.31.39:8081/ws', headers: userModel.user?.toJson());
              }
            },
          ),
        ],
      ),
      body: userModel.isLoggedIn
          ? _buildMessageContent(websocketModel)
          : _buildLoginPrompt(context),
    );
  }

  Widget _buildMessageContent(WebSocketModel websocketModel) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 自动滚动到底部
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });

    return Column(
      children: [
        // 连接状态指示器
        if (websocketModel.errorMessage != null)
          Container(
            padding: const EdgeInsets.all(8),
            color: Colors.red[50],
            child: Row(
              children: [
                const Icon(Icons.error, color: Colors.red, size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    websocketModel.errorMessage!,
                    style: const TextStyle(color: Colors.red, fontSize: 14),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close, size: 20),
                  onPressed: () {
                    websocketModel.clearError();
                  },
                ),
              ],
            ),
          ),
        // 消息显示区域
        Expanded(
          child: websocketModel.messages.isEmpty
              ? _buildEmptyMessageView(websocketModel)
              : ListView.builder(
                  controller: _scrollController,
                  itemCount: websocketModel.messages.length,
                  itemBuilder: (context, index) {
                    final message = websocketModel.messages[index];
                    final isSent = message['type'] == 'sent';
                    final timestamp = message['timestamp'] as DateTime;
                    final data = message['data'];

                    return Container(
                      margin: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      child: Align(
                        alignment: isSent
                            ? Alignment.centerRight
                            : Alignment.centerLeft,
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: isSent
                                ? Colors.blue[100]
                                : Colors.grey[300],
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Column(
                            crossAxisAlignment: isSent
                                ? CrossAxisAlignment.end
                                : CrossAxisAlignment.start,
                            children: [
                              Text(
                                data is String ? data : data.toString(),
                                style: const TextStyle(fontSize: 16),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '${timestamp.hour}:${timestamp.minute.toString().padLeft(2, '0')}',
                                style: const TextStyle(
                                    fontSize: 12, color: Colors.grey),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
        ),
        // 消息输入区域
        Container(
          padding: const EdgeInsets.all(8),
          decoration: const BoxDecoration(
            border: Border(top: BorderSide(color: Colors.grey)),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _messageController,
                  decoration: const InputDecoration(
                    hintText: '输入消息...',
                    border: OutlineInputBorder(),
                  ),
                  onSubmitted: (text) {
                    if (text.isNotEmpty && websocketModel.connected) {
                      websocketModel.sendMessage(text);
                      _messageController.clear();
                    }
                  },
                ),
              ),
              IconButton(
                icon: const Icon(Icons.send, color: Colors.blue),
                onPressed: websocketModel.connected &&
                        _messageController.text.isNotEmpty
                    ? () {
                        websocketModel.sendMessage(_messageController.text);
                        _messageController.clear();
                      }
                    : null,
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyMessageView(WebSocketModel websocketModel) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            websocketModel.connected
                ? Icons.chat_bubble_outline
                : Icons.cloud_off,
            size: 64,
            color: Colors.grey,
          ),
          const SizedBox(height: 16),
          Text(
            websocketModel.connected
                ? '连接已建立，暂无消息'
                : '未连接到服务器',
            style: const TextStyle(fontSize: 16, color: Colors.grey),
          ),
          const SizedBox(height: 8),
          Text(
            websocketModel.connected
                ? '开始发送消息吧'
                : '点击顶部图标连接到服务器',
            style: const TextStyle(fontSize: 14, color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _buildLoginPrompt(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.message,
            size: 80,
            color: Colors.grey,
          ),
          const SizedBox(height: 20),
          const Text(
            '登录后查看消息',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 30),
          ElevatedButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const Login(),
                ),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30),
              ),
            ),
            child: const Text(
              '登录/注册',
              style: TextStyle(
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }
}